﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infrastructure;
using System.Threading;
using DBDataAccessLib;
using System.Collections.ObjectModel;
using Microsoft.Practices.Prism.Commands;
using PluginManager;
using System.IO;
using System.Windows;
using System.IO.Ports;

namespace UploadImages.ViewModel
{
    public class UploadImagesViewModel : ViewModelBase
    {
        public UploadImagesViewModel()
        {
            GetWCNOLines();
            OpenFileCommand = new DelegateCommand<object>(OnOpenFileCommand);
            SaveCommand = new DelegateCommand<object>(OnSaveCommand, OnCanSaveCommand);
        }

        private void GetWCNOLines()
        {
            this.IsBusy = true;
            MessageContent = "正在获取流水线信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<string> stations = StationNameDataAccess.GetAllWCNOLines().ToObservableCollection();
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.WCNOLines = p as ObservableCollection<string>;
                    if (WCNOLines.Count > 0) this.SelectedWCNOLine = this.WCNOLines.First();
                }), stations);
            }), SynchronizationContext.Current);
        }

        public DelegateCommand<object> OpenFileCommand { get; set; }
        public DelegateCommand<object> SaveCommand { get; set; }

        public void OnOpenFileCommand(object obj)
        {
            ModalWindowService.ShowOpenFilesDialog("", "Image files(*.jpg,*.jpeg)|*.jpg;*.jpeg", imageNames =>
                {
                    selectedImageNames = string.Empty;
                    foreach (var imageName in imageNames)
                    {
                        selectedImageNames += imageName + "\r\n";
                    }
                    if (selectedImageNames.Length > 0)
                        SelectedImageNames = selectedImageNames.Substring(0, selectedImageNames.Length - 2);
                    SaveCommand.RaiseCanExecuteChanged();
                });
        }

        public void OnSaveCommand(object obj)
        {
            this.IsBusy = true;
            MessageContent = "正在上传文件...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
                {
                    SynchronizationContext context = currentContext as SynchronizationContext;
                    string message = string.Empty;
                    try
                    {
                        if (!Directory.Exists(Helper.ServerUrl)) Directory.CreateDirectory(Helper.ServerUrl);
                        if (!Directory.Exists(Helper.ServerUrl + SelectedWCNOLine)) Directory.CreateDirectory(Helper.ServerUrl + SelectedWCNOLine);
                        if (!Directory.Exists(Helper.ServerUrl + SelectedWCNOLine + "\\" + SelectedStationName)) Directory.CreateDirectory(Helper.ServerUrl +
                                    SelectedWCNOLine + "\\" + SelectedStationName);
                        //if (Directory.Exists(Helper.ServerUrl + SelectedStationName))
                        //{
                        //    if (!Directory.Exists(Helper.ServerUrl + "Template")) Directory.CreateDirectory(Helper.ServerUrl + "Template");
                        //    foreach (var item in Directory.GetFiles(Helper.ServerUrl + SelectedStationName))
                        //    {
                        //        FileInfo info = new FileInfo(item);
                        //        File.Copy(item, Helper.ServerUrl + "Template\\" + info.Name, true);
                        //    }
                        //    Directory.Delete(Helper.ServerUrl + SelectedStationName, true);
                        //}
                        //Directory.CreateDirectory(Helper.ServerUrl + SelectedStationName);

                        string existFiles = string.Empty;
                        string[] filePaths = SelectedImageNames.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        string[] serverPaths = Directory.GetFiles(Helper.ServerUrl + SelectedWCNOLine + "\\" + SelectedStationName);
                        foreach (var fPath in filePaths)
                        {
                            foreach (var sPath in serverPaths)
                            {
                                FileInfo fFileInfo = new FileInfo(fPath);
                                FileInfo sFileInfo = new FileInfo(sPath);
                                if (fFileInfo.Name.ToLower().Trim() == sFileInfo.Name.ToLower().Trim()) existFiles += sFileInfo.Name + ";";
                            }
                        }
                        if (existFiles.Length > 0) message = "在服务器上存在和上传的文件中同名的文件，上传失败。\r\n同名文件为:" +
                            existFiles.Substring(0, existFiles.Length - 1);
                        else
                        {
                            foreach (var path in filePaths)
                            {
                                FileInfo info = new FileInfo(path);
                                File.Copy(path, Helper.ServerUrl + SelectedWCNOLine + "\\" + SelectedStationName + "\\" + info.Name);
                            }
                            message = "上传成功";
                        }
                    }
                    catch (Exception ex)
                    {
                        message = "上传失败：" + ex.Message;
                        throw;
                    }

                    context.Send(new SendOrPostCallback(p =>
                    {
                        IsBusy = false;
                        ModalWindowService.ShowMessage(message);
                    }), null);
                }), SynchronizationContext.Current);
        }

        public bool OnCanSaveCommand(object obj)
        {
            return !string.IsNullOrWhiteSpace(this.SelectedImageNames) && !string.IsNullOrWhiteSpace(this.SelectedStationName) &&
                !string.IsNullOrWhiteSpace(this.SelectedWCNOLine);
        }

        private void GetStationNames()
        {
            this.IsBusy = true;
            MessageContent = "正在获取工位信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
                {
                    SynchronizationContext context = currentContext as SynchronizationContext;
                    ObservableCollection<string> stations = StationNameDataAccess.GetAllStationNames(SelectedWCNOLine).ToObservableCollection();
                    context.Send(new SendOrPostCallback(p =>
                        {
                            IsBusy = false;
                            this.StationNames = p as ObservableCollection<string>;
                            if (StationNames.Count > 0) this.SelectedStationName = this.StationNames.First();
                        }), stations);
                }), SynchronizationContext.Current);
        }

        private ObservableCollection<string> wcnoLines;

        public ObservableCollection<string> WCNOLines
        {
            get { return wcnoLines; }
            set
            {
                wcnoLines = value;
                OnPropertyChanged("WCNOLines");
            }
        }

        private string selectedWCNOLine;

        public string SelectedWCNOLine
        {
            get { return selectedWCNOLine; }
            set
            {
                if (selectedWCNOLine != value)
                {
                    selectedWCNOLine = value;
                    OnPropertyChanged("SelectedWCNOLine");
                    GetStationNames();
                    SaveCommand.RaiseCanExecuteChanged();
                }
            }
        }



        private ObservableCollection<string> stationNames;

        public ObservableCollection<string> StationNames
        {
            get { return stationNames; }
            set
            {
                stationNames = value;
                OnPropertyChanged("StationNames");
            }
        }

        private string selectedStationName;

        public string SelectedStationName
        {
            get { return selectedStationName; }
            set
            {
                selectedStationName = value;
                OnPropertyChanged("SelectedStationName");
                SaveCommand.RaiseCanExecuteChanged();
            }
        }

        private string selectedImageNames;

        public string SelectedImageNames
        {
            get { return selectedImageNames; }
            set
            {
                selectedImageNames = value;
                OnPropertyChanged("SelectedImageNames");
            }
        }
    }
}
